package com.yuexunit.mobilenurse.module.DocAdvice.presenter.impl;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.Dispensing_List_New;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.DocAdvice_Dispensing;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.DocAdvice_Dispensing_New;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.DocAdvice_OrderDetail;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.DocAdvice_OrderExec;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.DocAdvice_Orderlist;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.YXDocAdviceBean;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.YXExecuteOrder;
import com.yuexunit.mobilenurse.module.DocAdvice.model.IDispensingModel;
import com.yuexunit.mobilenurse.module.DocAdvice.presenter.IDispensingPresenter;
import com.yuexunit.mobilenurse.module.DocAdvice.ui.view.IDispensingView;
import com.yuexunit.mobilenurse.module.PatientDetail.model.impl.PatientDetailModel;
import com.yuexunit.mobilenurse.util.ProUtil;
import com.yuexunit.mobilenurse.util.RxUtils;

import org.json.JSONObject;
import org.kymjs.kjframe.ui.ViewInject;
import org.slf4j.Logger;

import java.util.ArrayList;
import java.util.List;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by work-jx on 2016/2/3.
 */
public class DispensingPresenter implements IDispensingPresenter{
    //记录Log
    private final Logger log = ProUtil.getLogger(PatientDetailModel.class);
    private IDispensingModel model;
    private IDispensingView view;
    private CompositeSubscription compositeSubscription = new CompositeSubscription();
    ArrayList<DocAdvice_Dispensing> docAdvice_all = new ArrayList<DocAdvice_Dispensing>();

    public DispensingPresenter(IDispensingView view,IDispensingModel model)
    {
        this.view = view;
        this.model = model;
    }


    @Override
    public void showDispensingList(String visitno) {
        compositeSubscription.add(
                model.getDispensingListData(visitno)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<String>() {
                            @Override
                            public void onCompleted() {
                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.e("jx",e+"");
                                ViewInject.toast("发药暂无数据");
                                view.showDispensingList(docAdvice_all);
                            }

                            @Override
                            public void onNext(String result) {
                                YXDocAdviceBean Total = JSON.parseObject(result, YXDocAdviceBean.class);
                                YXDocAdviceBean DocAdviceData = Total.getBody();
                                Log.v("jx", DocAdviceData.getHead().getRet_code());
                                if ("0".equals(DocAdviceData.getHead().getRet_code())) {

                                    List<DocAdvice_Orderlist> docadvice_orderlist;
                                    List<DocAdvice_OrderDetail> docadvice_orderdetail;
                                    List<DocAdvice_OrderExec> docAdvice_orderexec;

                                    String orderlist = DocAdviceData.getResponse().getOrderlist();
                                    String orderlist_first = orderlist.substring(0, 1);
                                    if (!orderlist_first.equals("[")) {
                                        orderlist = "[" + orderlist + "]";
                                        docadvice_orderlist = JSON.parseArray(orderlist, DocAdvice_Orderlist.class);
                                    } else {
                                        docadvice_orderlist = JSON.parseArray(orderlist, DocAdvice_Orderlist.class);
                                    }

                                    String orderdetail = DocAdviceData.getResponse().getOrderdetail();
                                    String orderdetail_first = orderdetail.substring(0, 1);
                                    if (!orderdetail_first.equals("[")) {
                                        orderdetail = "[" + orderdetail + "]";
                                        docadvice_orderdetail = JSON.parseArray(orderdetail, DocAdvice_OrderDetail.class);
                                    } else {
                                        docadvice_orderdetail = JSON.parseArray(orderdetail, DocAdvice_OrderDetail.class);
                                    }

                                    String orderexec = DocAdviceData.getResponse().getOrderexec();
                                    if (!("null".equals(orderexec))) {
                                        String orderexec_first = orderexec.substring(0, 1);
                                        if (!orderexec_first.equals("[")) {
                                            orderexec = "[" + orderexec + "]";
                                            docAdvice_orderexec = JSON.parseArray(orderexec, DocAdvice_OrderExec.class);
                                        } else {
                                            docAdvice_orderexec = JSON.parseArray(orderexec, DocAdvice_OrderExec.class);
                                        }
                                    } else {
                                        docAdvice_orderexec = null;
                                    }


                                    for (int i = 0; i < docadvice_orderlist.size(); i++) {
                                        DocAdvice_Dispensing docAdvice_dispensing = new DocAdvice_Dispensing();
                                        Log.v("jx", docadvice_orderlist.get(i).getInjectflag());
                                        if(!docadvice_orderlist.get(i).getOrdertype().equals("C")) {
                                            if (!(AppConfig.INJECTFLAG.equals(docadvice_orderlist.get(i).getInjectflag()))) {
                                                docAdvice_dispensing.setDocAdvice_orderlist(docadvice_orderlist.get(i));
                                                ArrayList<DocAdvice_OrderDetail> docAdvice_orderDetails = new ArrayList<DocAdvice_OrderDetail>();
                                                for (int j = 0; j < docadvice_orderdetail.size(); j++) {
                                                    if (docAdvice_dispensing.getDocAdvice_orderlist().getOrdergroupno() == docadvice_orderdetail.get(j).getOrdergroupno()) {
                                                        docAdvice_orderDetails.add(docadvice_orderdetail.get(j));
                                                    }
                                                }
                                                docAdvice_dispensing.setDespensing_detail(docAdvice_orderDetails);

                                                if (null != docAdvice_orderexec) {
                                                    int count = 0;
                                                    ArrayList<DocAdvice_OrderExec> doc_orderexec = new ArrayList<DocAdvice_OrderExec>();
                                                    for (int z = 0; z < docAdvice_orderexec.size(); z++) {
                                                        if (docAdvice_dispensing.getDocAdvice_orderlist().getOrdergroupno() == docAdvice_orderexec.get(z).getOdergroupno()) {
                                                            if (docAdvice_orderexec.get(z).getExecempid() == null) {
                                                                count++;
                                                            }
                                                            doc_orderexec.add(docAdvice_orderexec.get(z));
                                                        }
                                                    }
                                                    if (count > 0) {
                                                        docAdvice_dispensing.setCount(doc_orderexec.size() - count + "/" + doc_orderexec.size());
                                                        docAdvice_dispensing.setStatus("等待发药");
                                                    } else {
                                                        docAdvice_dispensing.setCount(doc_orderexec.size() - count + "/" + doc_orderexec.size());
                                                        docAdvice_dispensing.setStatus("已发药");
                                                    }
                                                    docAdvice_dispensing.setDespensing_exec(doc_orderexec);
                                                } else {
                                                    docAdvice_dispensing.setCount("0/0");
                                                    docAdvice_dispensing.setStatus("已发药");
                                                }
                                                docAdvice_all.add(docAdvice_dispensing);
                                            } else {
                                                Log.v("jx", "over");
                                            }
                                        }
                                    }
                                    if(docAdvice_all.size() == 0)
                                    {
                                        ViewInject.toast("发药暂无数据");
                                    }
                                }
                                view.showDispensingList(docAdvice_all);
                            }
                        }));
    }


    @Override
    public void Execorder(final boolean source,String visitno, String barcode, String nurseid) {
        compositeSubscription.add(
                model.ExecOrder(visitno, barcode, nurseid)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<String>() {

                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {
                                if(source) {
                                    view.execDialog(AppConfig.EXEC_DIALOG_UNPASS_EXTERNAL,AppConfig.NETERROR);
                                }else{
                                    view.execDialog(AppConfig.EXEC_DIALOG_UNPASS_INNER,AppConfig.NETERROR);
                                }
                            }

                            @Override
                            public void onNext(String result) {
                                JSONObject all, body;
                                String reponse = null;
                                try {
                                    all = new JSONObject(result.toString());
                                    body = all.getJSONObject("body");
                                    reponse = body.getString("response");
                                } catch (Exception e) {
                                    log.error("Exception:"+e);
                                    if(source) {
                                        view.execDialog(AppConfig.EXEC_DIALOG_UNPASS_EXTERNAL,AppConfig.NETERROR);
                                    }
                                    else {
                                        view.execDialog(AppConfig.EXEC_DIALOG_UNPASS_INNER,AppConfig.NETERROR);
                                    }
                                }

                                if(!("null".equals(reponse))) {
                                    YXExecuteOrder Total = JSON.parseObject((String) result.toString(), YXExecuteOrder.class);
                                    YXExecuteOrder executeOrderData = Total.getBody();

                                    if (source) {
                                        if ("0".equals(executeOrderData.getHead().getRet_code())) {
                                            view.execDialog(AppConfig.EXEC_DIALOG_PASS_EXTERNAL,"");
                                        } else {
                                            view.execDialog(AppConfig.EXEC_DIALOG_UNPASS_EXTERNAL,AppConfig.MISMATCH);
                                        }
                                    } else {
                                        if ("0".equals(executeOrderData.getHead().getRet_code())) {
                                            view.getExecData(executeOrderData);
                                           view.execDialog(AppConfig.EXEC_DIALOG_PASS_INNER,"");
                                        } else {
                                            view.execDialog(AppConfig.EXEC_DIALOG_UNPASS_INNER,AppConfig.MISMATCH);
                                        }
                                    }
                                }
                                else {
                                    if(source) {
                                        view.execDialog(AppConfig.EXEC_DIALOG_UNPASS_EXTERNAL,AppConfig.UNSUCESS);
                                    }
                                    else {
                                        view.execDialog(AppConfig.EXEC_DIALOG_UNPASS_INNER,AppConfig.UNSUCESS);
                                    }
                                }
                            }
                        })
        );
    }

    public CompositeSubscription getCompositeSubscription() {
        return RxUtils.getNewCompositeSubIfUnsubscribed(compositeSubscription);
    }

    public void UnSubObservers() {
        if (compositeSubscription != null && !compositeSubscription.isUnsubscribed()) {
            compositeSubscription.unsubscribe();
        }

    }
}
